<template>
  <div class="mx-auto p-3 w-330">
    <h5 class="my-4 text-center">登录</h5>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">邮箱地址</label>
        <validate-input placeholder="请输入邮箱地址" type="text" :rules="emailRules" v-model="emailVal" />
      </div>
      <div class="mb-3">
        <label class="form-label">密码</label>
        <validate-input type="password" placeholder="请输入密码" :rules="passwordRules" v-model="passwordVal" />
      </div>
      <template #submit>
        <button type="submit" class="btn btn-primary btn-block btn-large">登录</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { RuleProps } from "@/types";
import ValidateForm from "@/components/ValidateForm.vue";
import ValidateInput from "@/components/ValidateInput.vue";
import message from "@/components/message/index";

const store = useStore();
const router = useRouter();

const emailVal = ref("");
const passwordVal = ref("");
const emailRules: RuleProps[] = [
  { type: "required", message: "电子邮箱地址不能为空" },
  { type: "email", message: "请输入正确的电子邮箱格式" },
];
const passwordRules: RuleProps[] = [{ type: "required", message: "密码不能为空" }];

const onFormSubmit = async (result: boolean) => {
  if (result) {
    const params = {
      email: emailVal.value,
      password: passwordVal.value,
    };
    try {
      await store.dispatch("loginAndFetch", params);
      message("登录成功", "success");
      router.push("/");
    } catch {}
  }
};
</script>
